package ms.unicorn.erml.handles;

import ms.unicorn.erml.figures.CollapseFigureEx;
import ms.unicorn.erml.figures.HandleBoundEx;
import ms.unicorn.ui.edit.parts.IGraphicalEditPartEx;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Locator;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.handles.CompartmentCollapseHandle;
import org.eclipse.gmf.runtime.notation.DrawerStyle;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;

public class CompartmentCollapseHandleEx extends CompartmentCollapseHandle {

	/**
     * Positions the supplied figure in its owner.
     */
    private class CollapseHandleLocator implements Locator {
       
    	public void relocate(IFigure target) {
    		IGraphicalEditPart ownerParent = (IGraphicalEditPart) getOwner().getParent();
    		IFigure ownerParentFig = ownerParent instanceof IGraphicalEditPartEx ?
    			 ((IGraphicalEditPartEx) ownerParent).getPrimaryFigure() :	ownerParent.getFigure();
            Rectangle theBounds = null;
            if (ownerParentFig instanceof HandleBoundEx) {
                theBounds = ((HandleBoundEx) ownerParentFig)
                    .getAbsCollapseHandleBounds(true);
            } else {//it is a pool put it in the top left corner
                theBounds = ownerParentFig.getClientArea().getCopy();          
                ownerParentFig.translateToAbsolute(theBounds);
            }
            target.translateToRelative(theBounds);
            setBounds(theBounds);
        }
    }

    /**
     * Creates new instance of collapse handler.
     * 
     * @param owner
     */
    @SuppressWarnings("restriction")
	public CompartmentCollapseHandleEx(IGraphicalEditPart owner) {
        super(owner);
        setSize(1, 1);
        setLocator(new CollapseHandleLocator());
        remove(collapseFigure);
        add(collapseFigure = new CollapseFigureEx());
        View view = owner.getNotationView();
        if (view != null) {
            DrawerStyle style = (DrawerStyle) view
                    .getStyle(NotationPackage.eINSTANCE.getDrawerStyle());
            if (style != null) {
                collapseFigure.setCollapsed(style.isCollapsed());
                return;
            }
        }
        collapseFigure.setCollapsed(false);
    }

}
